package com.yksj.healthtalk.ui.doctorstation;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONArray;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog.OnDilaogClickListener;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog;
import com.yksj.healthtalk.entity.DoctorServiceAddTimeEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartControlClient;
import com.yksj.healthtalk.services.CoreService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.TimeUtil;
import com.yksj.healthtalk.utils.ToastUtil;
/**服务时段列表
 * 预约时间 选择服务时间段
 * @author Administrator
 *
 */
public class DoctorServiceTimeListActivity extends BaseFragmentActivity implements OnClickListener, OnItemClickListener, OnRefreshListener<ListView>, OnDilaogClickListener {

	private ListView mListView;
	private PullToRefreshListView refreshListView;
	private String mServiceTypeId;
	List<DoctorServiceAddTimeEntity> entities=new ArrayList<DoctorServiceAddTimeEntity>();
	private MyAdapter adapter;
	private String userId;//用户id
	private String PARAME="";//删除的数组数据
	private String TYPE="";
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.doctor_choice_data_mark_talk);
		initTitle();
		initView();
	}
    @Override
    protected void onStart() {
    	super.onStart();
		Intent intent =new Intent(this,CoreService.class);
		intent.setAction(CoreService.ACTION_FRAME_VIEW_VISIABLE);
		intent.putExtra("className",this.getClass().getName());
		startService(intent);
    }
	private void initView() {
		titleLeftBtn.setOnClickListener(this);
		titleRightBtn2.setVisibility(View.VISIBLE);
		titleRightBtn2.setOnClickListener(this);
		titleRightBtn2.setText("添加");
		
		titleRightBtn.setVisibility(View.VISIBLE);
		titleRightBtn.setOnClickListener(this);
		titleRightBtn.setText("编辑");
		
		titleTextV.setText("服务时段设置");
		
		mServiceTypeId = getIntent().getStringExtra("SERVICE_TYPE_ID");
		refreshListView = (PullToRefreshListView)findViewById(R.id.listview_fragment);
		mListView = refreshListView.getRefreshableView();
		adapter = new MyAdapter(entities, this,mServiceTypeId);
		mListView.setAdapter(adapter);
		mListView.setOnItemClickListener(this);
		refreshListView.setOnRefreshListener(this);
		View view = getLayoutInflater().inflate(R.layout.commn_empty_layout,null);
		((TextView)view.findViewById(R.id.empty_txt)).setText("还未添加服务时段");
		mListView.setEmptyView(view);
		
		findViewById(R.id.delete_all).setOnClickListener(this);
		findViewById(R.id.delete).setOnClickListener(this);
		userId = SmartControlClient.getControlClient().getUserId();
		initData();
	}
	private void initData() {
		HttpRestClient.doHttpChoiceDateMarkTalk(mServiceTypeId,new AsyncHttpResponseHandler(this){
			@Override
			public void onSuccess(int statusCode, String content) {
				super.onSuccess(statusCode, content);
				adapter.onBoundData(DoctorServiceAddTimeEntity.parToList(content));
				if("[]".equals(content)){
					titleRightBtn2.setText("添加");
				}
			}
			});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			setResult(RESULT_OK, getIntent());
			finish();
			break;
			
		case R.id.delete_all:// 删除所有
			String PARAME="";
			TYPE="deleteAllYuyueTime";
			deleteServiceListBefor(PARAME);
			break;
		case R.id.delete:// 删除
			TYPE="deleteSeleteYuyueTime";
			JSONArray array=new JSONArray();
			
			for (int i = 0; i < adapter.list.size(); i++) {
				if(adapter.list.get(i).isSeclect()){
					JSONObject object=new JSONObject();
					DoctorServiceAddTimeEntity entity = adapter.list.get(i);
					object.put("SERVICE_ITEM_ID", entity.getSERVICE_ITEM_ID());
					object.put("SERVICE_DAY", entity.getSERVICE_TIME_BEGIN().substring(0, 8));
					object.put("REPEAT_FLAG", entity.getREPEAT_FLAG());
					array.put(object);
				}
			}
			
			deleteServiceListBefor(array.toString());
			
			break;
		case R.id.title_right2:// 添加
			if(titleRightBtn.getVisibility()==View.GONE){
				adapter.changeList(1);
				titleRightBtn.setVisibility(View.VISIBLE);
				findViewById(R.id.delete_layout).setVisibility(View.GONE);
				titleRightBtn2.setText("添加");
			}else{
				Intent intent=new Intent(this,DoctorServiceAddTime.class);
				intent.putExtra("SERVICE_TYPE_ID", mServiceTypeId);
				intent.putParcelableArrayListExtra("entitys",(ArrayList<? extends Parcelable>) adapter.list);
				startActivityForResult(intent, 1000);
			}
			break;
		case R.id.title_right:// 编辑
			if(adapter.list.size()==0){
				ToastUtil.showShort("您尚未添加服务时段,不需要编辑");
				return;
			}
			adapter.changeList(0);
			titleRightBtn.setVisibility(View.GONE);
			titleRightBtn2.setText("完成");
			findViewById(R.id.delete_layout).setVisibility(View.VISIBLE);
			break;
		}	
	}
	
//	删除预约或者时段前所调用的接口
//	ServiceSetServlet33
//	Type=beforeDeleteYuyue
//	CUSTOMER_ID 客户id
//	SERVICE_TYPE_ID 类型id
//	PARAME 将服务项id（即SERVICE_ITEM_ID）装进数组打成jsonArray发过来  
//
//	返回参数：如果有error_code，则提示error_message并且不能继续往下操作
//		  没有则提示message
	
	//删除之前调用接口
	private void deleteServiceListBefor(final String PARAME) {
		HttpRestClient.doHttpDeleteServiceTimeBefor("beforeDeleteYuyue",userId,PARAME,new JsonsfHttpResponseHandler(this){
			@Override
			public void onSuccess(int statusCode, JSONObject response) {
				super.onSuccess(statusCode, response);
				if(response.containsKey("error_code")){
					String message=response.getString("error_message");
					SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(),  message);
				}else{
					DoctorServiceTimeListActivity.this.PARAME=PARAME;
					DoubleBtnFragmentDialog.showDefault(getSupportFragmentManager(),  "删除此时段后，您有义务完成已成功预约的服务，此时段将不会有新的预约，您确定删除此时段？", "放弃", "删除", DoctorServiceTimeListActivity.this);
//					DoubleBtnFragmentDialog.showDefault(getSupportFragmentManager(),  response.getString("message"), "放弃", "删除", DoctorServiceTimeListActivity.this);
				}
			}
		});
		
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode!=Activity.RESULT_OK)return;
		switch (requestCode) {
		case 1000:
//			initData();
			break;
		}
	}
	
	
	@Override
	protected void onRestart() {
		super.onRestart();
		initData();
	}
	
	class MyAdapter extends BaseAdapter{
		public List<DoctorServiceAddTimeEntity> list=new ArrayList<DoctorServiceAddTimeEntity>();
		Context context;
		private final String[] dateString=new String[]{"星期一","星期二","星期三","星期四","星期五","星期六","星期日"};
		private final String type;//时段2   面访3
		private int type_edit=1;//如果不是1表示编辑
		public MyAdapter(List<DoctorServiceAddTimeEntity> list,Context context,String mType) {
			this.list=list;
			this.context=context;
			this.type=mType;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		public void onBoundData(List<DoctorServiceAddTimeEntity> list){
			if(list==null)return;
			Collections.sort(list,new DoctorServiceAddTimeEntity());
			this.list.clear();
			this.list.addAll(list);
 			notifyDataSetChanged();
		}
		
		public void changeList(int type_edit){
			this.type_edit=type_edit;
			notifyDataSetChanged();
		}
		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final ViewHolder holder;
			final DoctorServiceAddTimeEntity entity=list.get(position);
			
			if(convertView==null){
				holder=new ViewHolder();
				convertView=LayoutInflater.from(context).inflate(R.layout.doctor_mark_talk_item, null);
				holder.setName=(TextView)convertView.findViewById(R.id.name);
				holder.setTime=(TextView)convertView.findViewById(R.id.time);
				holder.setDate=(TextView)convertView.findViewById(R.id.date);
				holder.ISSPECIAL=(TextView)convertView.findViewById(R.id.teshu_shoufei);
				holder.isSeclect=(CheckBox) convertView.findViewById(R.id.isSeclect);
				convertView.setTag(holder);
			}else{
				holder=(ViewHolder) convertView.getTag();
				}
			
				holder.setTime.setText(TimeUtil.getDemo(entity.getSERVICE_TIME_BEGIN(), entity.getSERVICE_TIME_END()));
				try {
					holder.setDate.setText(dateString[Integer.valueOf(entity.getWEEK())-1]);
				} catch (Exception e) {
					holder.setDate.setVisibility(View.INVISIBLE);
				}
				
				if("1".equals(entity.getISSPECIAL())){
					holder.ISSPECIAL.setVisibility(View.VISIBLE);
				}else{
					holder.ISSPECIAL.setVisibility(View.INVISIBLE);
				}
				
			holder.setName.setText(entity.getSERVICE_TYPE_ID().equals("2")?"网上咨询":"门诊预约");
			
			if(type_edit==1){
				holder.isSeclect.setVisibility(View.GONE);
			}else{
				holder.isSeclect.setVisibility(View.VISIBLE);
			}
			
			//用于批量删除  是否选中
			holder.isSeclect.setOnCheckedChangeListener(null);
			holder.isSeclect.setChecked(entity.isSeclect());
			holder.isSeclect.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				
				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					entity.setSeclect(isChecked);
				}
			});
			
			return convertView;
		}
		
		private class ViewHolder {
			TextView setName;
			TextView setTime;
			TextView setDate;
			TextView ISSPECIAL;//是否有特殊收费人群
			CheckBox isSeclect;//是否选中
		} 
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Intent intent=new Intent(this,DoctorServiceAddTime.class);
		Bundle bundle=new Bundle();
		bundle.putParcelable("entity", adapter.list.get(position-1));
		intent.putParcelableArrayListExtra("entitys",(ArrayList<? extends Parcelable>) adapter.list);
		intent.putExtra("SERVICE_TYPE_ID", adapter.list.get(position-1).getSERVICE_TYPE_ID());//mServiceTypeId
		intent.putExtras(bundle);
		startActivityForResult(intent, 1000);
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		refreshListView.onRefreshComplete();
	}
	@Override
	public void onDismiss(DialogFragment fragment) {
	}
	
	
	//删除操作
//	删除所有服务项
//	ServiceSetServlet33      
//	Type=deleteAllYuyueTime
//	CUSTOMER_ID 客户id
//	SERVICE_TYPE_ID 类型id
//	返回参数：如果有error_code，则提示error_message	
//	没有则成功
//	
//	删除选择服务项
//	ServiceSetServlet33
//	Type=deleteSeleteYuyueTime
//	PARAME 将服务项id（即SERVICE_ITEM_ID）装进数组打成jsonArray发过来  
//	CUSTOMER_ID 客户id
	@Override
	public void onClick(DialogFragment fragment, View v) {
		
		HttpRestClient.doHttpDeleteServiceTimeBefor(TYPE, userId, PARAME, new JsonsfHttpResponseHandler(this){
			@Override
			public void onSuccess(int statusCode, JSONObject response) {
				super.onSuccess(statusCode, response);
				if(response.containsKey("error_code")){
					SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(),  response.getString("error_message"));
				}else{
					initData();
				}
			}
		});
	}
	
}
